<?php
/**
 * Created by PhpStorm.
 * User: alexlz
 * Date: 9/29/14
 * Time: 12:47 PM
 */

namespace imgs;

use files\FileUtils;

if (!defined('NYMPH_ROOT')) {
    define('NYMPH_ROOT', dirname("../../../" . __FILE__));
    require(NYMPH_ROOT . '/local/loader/kernel/classes/URLClassLoader.php');
}

class ImageUtils implements IImageUtils{

    /**
     * (PHP 5)<br/>
     * Creates preview of one image in directory.
     * @param string $pathToImage
     * @param string $newWidth
     * @param string $outputDir
     * @param string $filesDir
     */
    static function createImagePreview($pathToImage, $newWidth, $outputDir, $filesDir)
    {

        $outputDir .= DIRECTORY_SEPARATOR . FileUtils::getRelativePath($pathToImage, $filesDir) . DIRECTORY_SEPARATOR;

        if (!file_exists($outputDir)) {
            mkdir($outputDir, 0777, true);
        }

        $targetPath = $outputDir . FileUtils::getFilePath($pathToImage);
        $size = getimagesize($pathToImage);
        $scale = $size[0] / $newWidth;
        $countedHeight = $size[1] / $scale;
        $source = self::createImageByType($pathToImage);
        $target = imagecreatetruecolor($newWidth, $countedHeight);

        imagecopyresampled(
            $target,
            $source,
            0, 0,
            0, 0,
            $newWidth,
            $countedHeight,
            $size[0],
            $size[1]
        );

        imagejpeg($target, $targetPath, 100);

        imagedestroy($target);
        imagedestroy($source);
    }

    /**
     * (PHP 5)<br/>
     * Creates images depends on path
     * @param string $pathToImage
     * @return  resource an image resource identifier on success, false on errors.
     */
    static function createImageByType($pathToImage)
    {
        $type = FileUtils::getFileExtension($pathToImage);
        switch (strtolower($type)) {
            case "jpg":
                return imagecreatefromjpeg($pathToImage);
            case "jpeg":
                return imagecreatefromjpeg($pathToImage);
            case "png":
                return imagecreatefrompng($pathToImage);
            case "gif":
                return imagecreatefromgif($pathToImage);
            default:
                return imagecreatefromjpeg($pathToImage);
        }
    }

    /**
     * (PHP 5)<br/>
     * Creates previews of all Images of directory.
     * @param string $filesDir
     * @param string $outputDir
     * @param int $width
     */
    static function createAllImagesPreview($filesDir, $outputDir, $width)
    {
        $files = FileUtils::getAllFilesFromDir($filesDir);
        foreach ($files as $key => $value) {
            self::createImagePreview($value, $width, $outputDir, $filesDir);
        }
    }
}